#!/usr/bin/env python
# -*- coding:utf-8 -*-
# Create by zhang
# Create on 2022/6/30 9:17
import os
from typing import List

from domain.report.common.period_enum import PeriodEnum
from config.config import config
from domain.report.common.period_mapper import PeriodMapper
from domain.report.spider.pdf_report.report_spider import report_spider

report_pdf_base = config.get("data", "report_pdf")


def get_pdf(stock_code: str, year: int, period: PeriodEnum = PeriodEnum.all) -> List[str]:
    stock_id = stock_code.split(".")[0]
    stock_path = os.path.join(report_pdf_base, stock_id)
    pdf_list = list()
    if os.path.exists(stock_path):
        file_list = os.listdir(stock_path)
        pattern_list = ["{}_{}_{}_".format(stock_id, p, year) for p in PeriodMapper.get_zh_period(period)]
        for p in pattern_list:
            for f in file_list:
                if f.startswith(p):
                    pdf_list.append(f)
    if pdf_list is None or len(pdf_list) == 0:
        report_spider(stock_code, year, period)

    if (pdf_list is None or len(pdf_list) == 0) and os.path.exists(stock_path):
        file_list = os.listdir(stock_path)
        pattern_list = ["{}_{}_{}_".format(stock_id, p, year) for p in PeriodMapper.get_zh_period(period)]
        for p in pattern_list:
            for f in file_list:
                if f.startswith(p):
                    pdf_list.append(f)
    return pdf_list
